﻿using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;

namespace EssentialWebFramework.Common.Middlewares
{
    /// <summary>
    /// 请求的 BodyStream 优化中间件（启用 Rewind 以反复读取）
    /// </summary>
    public class RequestBodyStreamOptimizeMiddleware
    {
        /// <summary>
        /// next
        /// </summary>
        private RequestDelegate _next;

        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="next"></param>
        public RequestBodyStreamOptimizeMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        /// <summary>
        /// Invoke
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            if (!context.WebSockets.IsWebSocketRequest && !context.Request.HasFormContentType)
            {
                context.Request.EnableBuffering();
            }
            
            await _next(context);
        }
    }
}
